package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * title:
 * author: Gyh
 * date:2023-04-18 20:07
 * Description:
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    /**
     * 文件（图片）上传到MinIO云，并获取文件在线地址用于前端展示
     * @param file
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            //todo:创建存储空间 ****该存储空间要设置为public****
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            //使用UUID创建新上传文件对象的标识
            //获取文件后缀名称
            String name = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            //生成的UUID拼接文件后缀名称-->上传后文件的名称
            String fileName = DateUtil.formatDate(new Date()) + "/" + UUID.randomUUID().toString().replaceAll("-","")+"."+name;
            //调用minioClient方法上传文件
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );
            //拼接上传的文件地址
            return endpointUrl + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
